package com.zhiwang.xiaoqu.mvp.presenter

import android.os.Environment
import androidSchedule
import com.zhiwang.xiaoqu.di.annotation.ActivityScope
import com.zhiwang.xiaoqu.mvp.model.RestApi
import com.zhiwang.xiaoqu.util.FormatUtil
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject

@ActivityScope
class UtilPresenter @Inject constructor(var restApi: RestApi) {


    interface CallBack {
        fun onDownLoadComplete(f: File)
    }

    /**
     * 仅限于快速下载单张图片或者小文件
     */
    fun downLoadFile(url: String, cb: CallBack) {
        with(restApi) {
            downloadFile(url)
                .androidSchedule()
                .map {
                    val stream = it.byteStream()
                    val fileHeader = ByteArray(8)
                    stream.read(fileHeader)

                    val format = FormatUtil.getImageFormat(fileHeader)
                    val fileName = SimpleDateFormat.getTimeInstance().format(Date()).plus(".$format")
                    val filePath = File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                        "趣味星球" + File.separator + fileName
                    )
                    if (filePath.parentFile.exists().not()) filePath.parentFile.mkdirs()
                    if (filePath.exists().not()) filePath.createNewFile()
                    val bufFos = BufferedOutputStream(FileOutputStream(filePath))
                    val buffer = ByteArray(4096)
                    var byteRead = -1
                    bufFos.write(fileHeader)
                    while (stream.read(buffer).also { byteRead = it } != -1) {
                        bufFos.write(buffer, 0, byteRead)
                        bufFos.flush()
                    }
                    bufFos.close()
                    stream.close()
                    return@map filePath
                }.subscribe {
                    cb.onDownLoadComplete(it)
                }
        }
    }
}